package com.xoa.service.workflow.flowformtype;

import com.xoa.dao.department.DepartmentMapper;
import com.xoa.dao.users.UsersMapper;
import com.xoa.dao.workflow.FlowFormTypeMapper;
import com.xoa.model.users.Users;
import com.xoa.model.workflow.*;
import com.xoa.service.WFE.WFELog.WFELog;
import com.xoa.service.workflow.wrapper.FlowFormWrappers;
import com.xoa.util.Constant;
import com.xoa.util.CookiesUtil;
import com.xoa.util.common.CheckCallBack;
import com.xoa.util.common.StringUtils;
import com.xoa.util.common.session.SessionUtils;
import com.xoa.util.common.wrapper.BaseWrapper;
import org.apache.poi.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * Created by 韩东堂 on 2017/5/10.
 */
@Service
public class FlowFormService {

    @Autowired
    FlowFormTypeMapper flowFormTypeMapper;
    @Autowired
    private WFELog wfeLog;
    @Autowired
    private UsersMapper usersMapper;
    @Autowired
    private DepartmentMapper departmentMapper;
    /**
     * 创建作者:   韩东堂
     * 创建日期:   2017/5/12 16:55
     * 方法介绍:   根据FormId获取所有表单
     * 参数说明:   获取页面传递对象参数
     * @return
     */
    public FlowFormWrappers getFormBySortId(Integer sortId){
        FlowFormWrappers wrappers =new FlowFormWrappers();
       List<FlowFormType> datas= flowFormTypeMapper.selectFormBySort(sortId);
       if(datas!=null&&datas.size()>0){
           //将deptId为0的deptName强制改为全部部门
           for(int i=0;i<datas.size();i++){
               FlowFormType flowFormType=datas.get(i);
               if(flowFormType.getDeptId()!=null&&flowFormType.getDeptId().equals(0)){
                   flowFormType.setDepName("全部部门");
                   datas.set(i,flowFormType);
               }

           }
           wrappers.setDatas(datas);
           wrappers.setStatus(true);
           wrappers.setFlag(true);
           wrappers.setMsg("数据请求成功");
       }else{
           wrappers.setStatus(true);
           wrappers.setFlag(false);
           wrappers.setMsg("没有数据了，请新建...");
       }
//        wrappers.setDatas();
        return wrappers;
    }


    /**
     * Created by:   韩东堂
     * date:   2017/5/16 09:45
     * description:   模糊搜索（根据表单名称）
     * @param searchValue 搜索关键字
     * @param sortId 所属分类（保留字段）
     * @return
     */
    public FlowFormWrappers seachForm(String searchValue,Integer sortId){
        FlowFormWrappers wrapper =new FlowFormWrappers();

        if(StringUtils.checkNull(searchValue)){
            wrapper.setMsg("搜素字段不能为空");
            wrapper.setFlag(false);
            wrapper.setStatus(true);
            return wrapper;
        }
        List<FlowFormType> datas =  flowFormTypeMapper.queryBySearchValue(searchValue,sortId);
        if(datas!=null&&datas.size()>0){
            wrapper.setDatas(datas);
            wrapper.setStatus(true);
            wrapper.setFlag(true);
            wrapper.setMsg("数据请求成功");
        }else{
            wrapper.setStatus(true);
            wrapper.setFlag(false);
            wrapper.setMsg("没有数据了，请新建...");
        }
        return wrapper;
    }

    /**
     * Created by:   韩东堂
     * date:   2017/5/16 10:47
     * description:   新建表单（根据表单名称）
     * @param formName 表单名称
     * @param deptId   部门Id
     * @param formSort 表单分类Id
     * @param otherinfo 其他预留信息（导入的时候使用，json串）
     * @return
     */
    public BaseWrapper newForm(String formName,Integer deptId,Integer formSort,String otherinfo){
        BaseWrapper wrapper =new BaseWrapper();
        if(StringUtils.checkNull(formName)){
            wrapper.setFlag(false);
            wrapper.setStatus(true);
            wrapper.setMsg("表单名称不能为空");
            return wrapper;
        }
        FlowFormType flowFormType =new FlowFormType();
        flowFormType.setFormName(formName);
        flowFormType.setDeptId(deptId);
        flowFormType.setFormSort(formSort);
        flowFormType.setPrintModel(otherinfo);
        int res = flowFormTypeMapper.insertSelectParam(flowFormType);
        if(res>0){
            wrapper.setFlag(true);
            wrapper.setStatus(true);
            wrapper.setMsg("新建表单成功");

            //lr 添加工作流程设计日志---新建表单
            HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
            FlowManageLog flowManageLog=wfeLog.getFlowManageLog(request);
            flowManageLog.setType(Constant.DESIGNTYPE1);
            flowManageLog.setTableName(formName);
            flowManageLog.setFlowId(0000);
            flowManageLog.setFlowName("表单");
            wfeLog.addFlowManageLog(flowManageLog);
            if(!StringUtils.checkNull(otherinfo)){
                //lr 添加工作流程设计日志---导入表单
                flowManageLog.setType(Constant.DESIGNTYPE19);
                flowManageLog.setTableName(formName);
                flowManageLog.setFlowId(0000);
                flowManageLog.setFlowName("表单");
                flowManageLog.setAuthorityName(formName);
                wfeLog.addFlowManageLog(flowManageLog);
            }
        }else{
            wrapper.setFlag(false);
            wrapper.setStatus(true);
            wrapper.setMsg("新建表单失败");
        }

        return wrapper;
    }

    /**
     * Created by:   韩东堂
     * date:   2017/5/16 15:47
     * description:   更新表单（根据表单id）
     * @param formId  表单Id
     * @param formName 表单名称
     * @param deptId  部门Id
     * @param formSort 分类Id
     * @param otherinfo 其他信息
     * @return
     */
    public BaseWrapper updateForm(Integer formId,String formName,Integer deptId,Integer formSort,String otherinfo){
        BaseWrapper wrapper =new BaseWrapper();
        if(StringUtils.checkNull(formName)){
            wrapper.setFlag(false);
            wrapper.setStatus(true);
            wrapper.setMsg("表单名称不能为空");
            return wrapper;
        }
        if(formId==null){
            wrapper.setFlag(false);
            wrapper.setStatus(true);
            wrapper.setMsg("表单Id不能为空");
            return wrapper;
        }
        FlowFormTypeExtends flowFormType =new FlowFormTypeExtends();
        flowFormType.setFormName(formName);
        flowFormType.setDeptId(deptId);
        flowFormType.setFormSort(formSort);
        flowFormType.setFormId(formId);
        if(!StringUtils.checkNull(otherinfo)){
            flowFormType.setPrintModel(otherinfo);
        }
        int res =flowFormTypeMapper.updateSelectParam(flowFormType);
        if(res>0){
            wrapper.setFlag(true);
            wrapper.setStatus(true);
            wrapper.setMsg("更新表单成功");
            //lr 添加工作流程设计日志---编辑表单
            HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
            FlowManageLog flowManageLog=wfeLog.getFlowManageLog(request);
            flowManageLog.setType(Constant.DESIGNTYPE18);
            flowManageLog.setTableName(formName);
            flowManageLog.setFlowId(0000);
            flowManageLog.setFlowName("表单");
            flowManageLog.setAuthorityName(formName);
            wfeLog.addFlowManageLog(flowManageLog);
            if(!StringUtils.checkNull(otherinfo)){
                //lr 添加工作流程设计日志---导入表单
                flowManageLog.setType(Constant.DESIGNTYPE19);
                flowManageLog.setTableName(formName);
                flowManageLog.setFlowId(0000);
                flowManageLog.setFlowName("表单");
                flowManageLog.setAuthorityName(formName);
                wfeLog.addFlowManageLog(flowManageLog);
            }
        }else{
            wrapper.setFlag(false);
            wrapper.setStatus(true);
            wrapper.setMsg("更新表单失败");
        }

        return wrapper;
    }

    /**
     * Created by:   韩东堂
     * date:   2017/5/17 09:49
     * description:   删除表单（根据表单id）
     * @param formId  表单Id
     * @return
     */
     public BaseWrapper deleteForm(Integer formId){
         BaseWrapper wrapper =new BaseWrapper();
         if(formId==null){
             wrapper.setFlag(false);
             wrapper.setStatus(true);
             wrapper.setMsg("表单Id不能为空");
             return wrapper;
         }
         //检查表单是非被流程占用
         int useNumber = flowFormTypeMapper.checkFormUserNumber(formId);
         if(useNumber>0){
             wrapper.setFlag(false);
             wrapper.setStatus(true);
             wrapper.setMsg("表单被占用，请先解除关联或删除对应流程");
             return wrapper;
         }

         //查询表单名称
         FlowFormType formName = flowFormTypeMapper.qureyItemMax(formId);
         //是 返回失败操作
         //否 删除表单
         int res= flowFormTypeMapper.deleteForm(formId);

         if(res>0){
             wrapper.setFlag(true);
             wrapper.setStatus(true);
             wrapper.setMsg("删除成功");
             //lr 添加工作流程设计日志---编辑表单
             HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
             FlowManageLog flowManageLog=wfeLog.getFlowManageLog(request);
             flowManageLog.setType(Constant.DESIGNTYPE20);
             flowManageLog.setTableName(formName.getFormName());
             flowManageLog.setFlowId(0000);
             flowManageLog.setFlowName("表单");
             flowManageLog.setAuthorityName(formName.getFormName());
             wfeLog.addFlowManageLog(flowManageLog);
         }else{
             wrapper.setFlag(false);
             wrapper.setStatus(true);
             wrapper.setMsg("操作失败");
         }
         return wrapper;
     }

    public BaseWrapper updateFormType(Integer formId,String formName,Integer deptId,Integer formSort,String printModel,Integer itemMax,String script,String css){
        BaseWrapper wrapper =new BaseWrapper();

        if(formId==null){
            wrapper.setFlag(false);
            wrapper.setStatus(true);
            wrapper.setMsg("表单Id不能为空");
            return wrapper;
        }


        FlowFormTypeExtends flowFormType =new FlowFormTypeExtends();
         flowFormType.setFormId(formId);
         if(!StringUtils.checkNull(printModel)){
             flowFormType.setPrintModel(printModel);
             flowFormType.setPrintModelShort(printModel);
             flowFormType.setItemMax(itemMax);
         }
         if (!StringUtils.checkNull(script)){
             flowFormType.setScript(script);
         }
        if (!StringUtils.checkNull(css)){
            flowFormType.setCss(css);
        }


        int res =flowFormTypeMapper.updateSelectParam(flowFormType);
        if(res>0){
            wrapper.setFlag(true);
            wrapper.setStatus(true);
            wrapper.setMsg("更新表单成功");
            /*  添加工作流程日志---保存表单  */
            HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
            FlowManageLog flowManageLog=wfeLog.getFlowManageLog(request);
            flowManageLog.setType(Constant.DESIGNTYPE2);
            flowManageLog.setFlowName("表单");
            flowManageLog.setFlowId(0000);
            if(formName==null||formName.equals("")){
                FlowFormType flowFormType1=flowFormTypeMapper.qureyItemMax(formId);
                formName=flowFormType1.getFormName();
            }
            flowManageLog.setTableName(formName);
            wfeLog.addFlowManageLog(flowManageLog);
        }else{
            wrapper.setFlag(false);
            wrapper.setStatus(true);
            wrapper.setMsg("更新表单失败");
        }

        return wrapper;
    }


    public FlowFormWrappers getFormByAll() {
        FlowFormWrappers wrappers =new FlowFormWrappers();
        List<FlowFormType> redatas =  flowFormTypeMapper.selectAllForm();

        List<FlowFormTypeParentModel> datas = formatForm(redatas);
        if(datas!=null&&datas.size()>0){
            wrappers.setDatas(datas);
            wrappers.setStatus(true);
            wrappers.setFlag(true);
            wrappers.setMsg("数据请求成功");
        }else{
            wrappers.setStatus(true);
            wrappers.setFlag(false);
            wrappers.setMsg("没有数据了，请新建...");
        }
        return wrappers;
    }

    private List<FlowFormTypeParentModel> formatForm(List<FlowFormType> redatas) {
        List<FlowFormTypeParentModel>  ret =new ArrayList<FlowFormTypeParentModel>();
        Map<String,List<FlowFormType>> map= new TreeMap<String,List<FlowFormType>>(new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                return o1.compareTo(o2);
            }
        });
        List<FlowFormType> flist =new ArrayList<FlowFormType>();
        for(FlowFormType form:redatas){
            Integer sortId = form.getFormSort();
            if(sortId==null||sortId==0){
                sortId=-1;
            }
            String keyId=String.valueOf(sortId);
            flist =  map.get(keyId);
            if(flist==null){
                flist=new ArrayList<FlowFormType>();
            }
            flist.add(form);
            map.put(keyId,flist);
        }
        for(Map.Entry<String,List<FlowFormType>> entry:map.entrySet()){
            FlowFormTypeParentModel model =new FlowFormTypeParentModel();
            if("-1".equals(entry.getKey())){
                model.setSortName("未分类");
                model.setForm( entry.getValue());
                ret.add(model);
            }else {
                List<FlowFormType> child =    entry.getValue();
                String name ="未知类型";
                if(child!=null&&child.size()>0){
                    name =  child.get(0).getSortName();
                }
                model.setSortName(name);
                model.setForm( entry.getValue());
                ret.add(model);
            }
        }
        return  ret;
    }

    public FlowFormWrappers getFormByDept(HttpServletRequest request) {
        FlowFormWrappers wrappers =new FlowFormWrappers();
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users users =  SessionUtils.getSessionInfo(request.getSession(),Users.class,new Users(),redisSessionCookie);
        //查看当前用户角色，为oa管理员可以看所有
        Users userPriv=usersMapper.getByUid(users.getUid());
        List<FlowFormType> redatas=new ArrayList<>();
        if(userPriv.getUserPriv().equals(1)){
            redatas =  flowFormTypeMapper.selectAllForm();
        }else{
            //获得当前用户可以看的部门
            Integer deptId=getAllDeptId(userPriv.getDeptId());
            redatas=flowFormTypeMapper.selectFormByDeptId(deptId);
        }
        List<FlowFormTypeParentModel> datas = formatForm(redatas);
        if(datas!=null&&datas.size()>0){
            wrappers.setDatas(datas);
            wrappers.setStatus(true);
            wrappers.setFlag(true);
            wrappers.setMsg("数据请求成功");
        }else{
            wrappers.setStatus(true);
            wrappers.setFlag(false);
            wrappers.setMsg("没有数据了，请新建...");
        }
        return wrappers;
    }

    //查找当前deptId的最上级
    public Integer getAllDeptId(Integer deptId){
        while (true){
            Integer parentId=departmentMapper.getParenDeptIdBydeptId(deptId);
            if(parentId==0){
                return deptId;
            }else{
                deptId=parentId;
            }
        }
    }
}
